import Vue from 'vue'
import VueRouter from 'vue-router'
import { getStorage } from '@/utils/storage.js'
Vue.use(VueRouter)
// 懒加载为了app.js小一点,打开网页快一点
// 为了让路由匹配上时,再去引入相应的页面
// 需要先执行npx webpack -v，版本大于4.2的时候才能用/* webpackChunkName: "login" */
const routes = [
  {
    path: '/',
    redirect: '/layout/home'
  },
  {
    path: '/login',
    component: () =>
      import(/* webpackChunkName: "login" */'@/views/login/index.vue'),
    // 组件独享为beforeEnter
    beforeEnter (to, form, next) {
      if (getStorage('geek-itheima')?.length > 0) {
        // 如果token存在的话就直接去首页,不让进入登录页
        next({ path: '/layout/home', replace: true }) // 去首页
      } else {
        next() // 放行
      }
    }
  },
  {
    path: '/seach',
    component: () =>
      import(/* webpackChunkName: "seach" */'@/views/Seach/Seach.vue')
  },
  {
    // 动态路由
    path: '/seachResult/:kw',
    component: () =>
      import(/* webpackChunkName: "seachResult" */'@/views/Seach/SearchResult.vue')
  },
  {
    path: '/userEdit',
    component: () =>
      import(/* webpackChunkName: "userEdit" */'@/views/User/userEdit.vue')
  },
  {
    path: '/chat',
    component: () =>
      import(/* webpackChunkName: "chat" */'@/views/Chat/index.vue')
  },
  {
    path: '/ArticleDetail',
    component: () =>
      import(/* webpackChunkName: "ArticleDetail" */'@/views/ArticleDetail/index.vue')
  },
  {
    path: '/layout',
    component: () =>
      import(/* webpackChunkName: "layout" */'@/views/layout/layout.vue'),
    children: [
      {
        path: 'home',
        component: () =>
          import(/* webpackChunkName: "home" */'@/views/Home/home.vue'),
        meta: {
          scrollT: 0 // 离开时滚动条的位置
        }
      }, {
        path: 'user',
        component: () =>
          import(/* webpackChunkName: "user" */'@/views/User/user.vue')
      }
    ]
  }]

const router = new VueRouter({
  routes
})
// 全局守卫beforeEach
// 登录后不让进登录页面
// router.beforeEach((to, form, next) => {
//   if (getStorage('geek-itheima')?.length > 0 && to.path === '/login') {
//     next({ path: '/layout/home', replace: true }) // 留在原地
//   } else {
//     next() // 放行
//   }
// })

export default router
